package cn.kogee.basic.controller;

import cn.kogee.basic.exception.BusinessException;
import cn.kogee.basic.util.AjaxResult;
import cn.kogee.basic.util.FastDfsUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {
    @PostMapping
    public AjaxResult upload(@RequestPart("file") MultipartFile file) {
        try {
            //http://123.207.27.208/group1/M00/00/71/CgAIC2LL6seAK9PUAABEaopyBV8726.jpg
            //获取文件名
            String filename = file.getOriginalFilename();
            //获得文件格式
            String extName = filename.substring(filename.lastIndexOf(".") + 1);
            //返回给前端相关值
            String uploadFile = FastDfsUtils.upload(file.getBytes(), extName);
            return AjaxResult.me().setResultObj(uploadFile);
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("网络繁忙上传失败");
        }
    }
    @DeleteMapping("path")
    public AjaxResult delete(@PathVariable("path") String path){
        try {
            ///group1/M00/00/71/CgAIC2LL6seAK9PUAABEaopyBV8726.jpg
            //获得组名
            //group1/M00/00/71/CgAIC2LL6seAK9PUAABEaopyBV8726.jpg
            String substring = path.substring(1);
            //group1
            String groupName = substring.substring(0, substring.indexOf("/"));
            //获得后续文件名
            //M00/00/71/CgAIC2LL6seAK9PUAABEaopyBV8726.jpg
            String fileName = path.substring(path.lastIndexOf("/") + 1);
            //调用方法删除
            FastDfsUtils.delete(groupName,fileName);
            //返回成功消息
            return AjaxResult.me();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("网络繁忙删除失败");
        }
    }
}
